package com.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class HT_Log {

    public static boolean isDebug = true;

    public static final String ROOT_DIR = "/sdcard" + "/hellotalk/";

    public static DateFormat formatter = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
    private static final StringBuffer strbuf = new StringBuffer();
    public static final String LOG_DIR = ROOT_DIR + "htlog/";

    protected static final String TAG = "HT_Log";

    private static WriteLogThread thread = null;
    private static Handler handler = null;
    // private static final int MSG_DESTROY = 1;

    private static SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS", Locale.getDefault());
    private static Runnable destroyRunnable = new Runnable() {
        @Override
        public void run() {
            if (thread != null) {
                thread.quit();
            }

            Log.d(TAG, "destroyRunnable");
            thread = null;
        }
    };

    private static Runnable writeRunnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "writeRunnable");
            handler.removeCallbacks(this);
            if (thread != null) {
                thread.writeLog();
            }
        }
    };

    // 提示消息
    public static void ShowTask(final Context context, final String content) {
        // 让其在主线程(UI线程)中运�?
        new Handler(Looper.getMainLooper()).post(new Runnable() {

            public void run() {
                Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Toast 显示消息
     * 
     * @param context
     * @param content
     */
    public static void Show(Context context, String content) {
        Toast.makeText(context, content, Toast.LENGTH_SHORT).show();
    }

    public static void Show(Context context, int resId) {
        Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
    }

    public static void ShowLong(Context context, String content) {
        Toast.makeText(context, content, Toast.LENGTH_LONG).show();
    }

    /**
     * 打印语句都用这个！！�?方便在打包是屏蔽�?��打印语句
     * 
     * @param content
     */
    /*
     * public static void Show(Object content) { if (isDebug) {
     * System.out.println("Debug:"+content); } }
     */

    public static void Show(String tag, Object content) {
        if (isDebug) {
            System.out.println(tag + ":" + content);
        }
    }

    public static void saveLog(String str) {

        strbuf.append(dataFormat.format(new Date()));
        strbuf.append(" ");
        if (str != null) {
            strbuf.append(str);
            strbuf.append("\n");
        } else {
            strbuf.append("退出service");
            strbuf.append("\n");
        }

        if (thread == null) {
            thread = new WriteLogThread();
            thread.start();
            handler = new Handler(thread.getLooper());
        }

        handler.removeCallbacks(destroyRunnable);
        handler.postDelayed(writeRunnable, 500);
        handler.postDelayed(destroyRunnable, 3000);
    }

    public static String getTrace(Throwable t) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }

    /*
     * @保存当天的文件3天日志
     * 
     * @file 删除文件的目录
     */

    public static boolean deleteFoder(String strfile) {
        File file = new File(strfile);
        Long lastmodifiletime;
        Long curtime = System.currentTimeMillis() / 1000 - 86400 * 3;
        if (file.exists()) {
            if (file.isDirectory()) {
                File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
                if (files != null) {
                    for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
                        lastmodifiletime = files[i].lastModified() / 1000;
                        if (lastmodifiletime < curtime && files[i].getName() != "htdb.xml") {
                            Show("deleteFoder", "-------" + files[i].getName() + "----");
                            // deleteFoder(files[i]); // 把每个文件 用这个方法进行迭代
                            files[i].delete();
                        }
                    }
                }
            }
        }
        return true;
    }

    // 打印错误信息
    public static void e(String tag, Throwable t) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        e(tag, buffer.toString());
    }

    // 打印错误信息
    public static void e(String tag, String log) {
        Log.e(tag, log);

        saveLog(tag + " " + log);
    }

    public static void d(String tag, String log) {
        Log.d(tag, log);
    }

    public static void w(String tag, String log) {
        Log.w(tag, log);

        saveLog(tag + " " + log);
    }

    static class WriteLogThread extends HandlerThread {
        File file = new File(LOG_DIR);
        FileWriter writer = null;
        BufferedWriter bw = null;

        public WriteLogThread() {
            super("log");

        }

        public void writeLog() {
            try {
                if (bw == null) {
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    try {
                        String httime = formatter.format(new Date());
                        String fileName = httime + ".log";
                        final File file2 = new File(LOG_DIR, fileName);
                        if (!file2.exists()) {
                            file2.createNewFile();
                        }
                        writer = new FileWriter(file2, true);
                        bw = new BufferedWriter(writer);
                    } catch (Exception e) {

                    }
                }

                if (bw != null && (strbuf.length() > 0)) {
                    bw.write(strbuf.toString());
                    bw.newLine();
                    bw.flush();
                    Log.d(TAG, "writeLog finish");
                } else {
                    Log.w(TAG, "writeLog ignore");
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                strbuf.setLength(0);
            }
        }

        @Override
        public boolean quit() {
            super.quit();
            writeLog();

            if (bw != null) {
                try {
                    bw.close();
                } catch (Exception e) {
                }
            }

            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                }
            }
            return super.quit();
        }
    }

}
